﻿using System;
using System.Linq;
using System.Reflection;
using System.Web.Http;
using System.Web.Mvc;
using SimpleInjector;
using SimpleInjector.Integration.Web;
using SimpleInjector.Integration.Web.Mvc;

namespace JuCheap.WebUI
{
    public class IOCConfig
    {
        /// <summary>
        /// Register
        /// </summary>
        public static void Register()
        {
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

            // Register your types, for instance:
            container.Register(() => GlobalConfiguration.Configuration, Lifestyle.Scoped);

            Load(container);

            // This is an extension method from the integration package.
            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

            // This is an extension method from the integration package as well.
            container.RegisterMvcIntegratedFilterProvider();

            container.Verify();

            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }

        static void Load(Container container)
        {
            var registrations =
                from type in
                    Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "/bin/JuCheap.Service.dll").GetTypes()
                where type.Namespace == "JuCheap.Service.AppService" && type.GetInterfaces().Any()
                select new {Service = type.GetInterfaces().First(), Implementation = type};

            foreach (var reg in registrations)
            {
                container.Register(reg.Service, reg.Implementation, Lifestyle.Scoped);
            }
        }
    }
}
